package com.yonyou.dmm.plugin;

import cn.hutool.core.convert.Convert;
import com.yonyou.iuap.ucf.common.exception.BusinessException;
import com.yonyou.ucf.mdd.ext.dao.meta.MetaDaoHelper;
import com.yonyou.ypd.bill.annotation.BillPlugin;
import com.yonyou.ypd.bill.context.YpdBillContext;
import com.yonyou.ypd.bill.plugin.AbstractBillPlugin;
import com.yonyou.dmm.mapper.DMMExpenseCardMapper;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * dmm经费卡插件
 */
@BillPlugin(busiObj = "dmm_apply_order", code = "dmm_apply_order")
public class DMMApplyOrderPlugin extends AbstractBillPlugin {

    @Autowired
    private DMMExpenseCardMapper expenseCardMapper;

    @Override
    public void beforeSubmit(YpdBillContext billContext) throws Exception {
        Map<String, BigDecimal> projectMoneyMap = getProjectMoney(billContext);
        for (Map.Entry<String, BigDecimal> pm : projectMoneyMap.entrySet()) {
            String project = pm.getKey();
            BigDecimal money = pm.getValue();
            expenseCardMapper.updateOccupyByProject(project, money);
        }
        super.beforeSubmit(billContext);
    }

    @Override
    public void beforeUnSubmit(YpdBillContext billContext) throws Exception {
        Map<String, BigDecimal> projectMoneyMap = getProjectMoney(billContext);
        for (Map.Entry<String, BigDecimal> pm : projectMoneyMap.entrySet()) {
            String project = pm.getKey();
            BigDecimal money = pm.getValue();
            expenseCardMapper.updateOccupyByProject(project, money.negate());
        }
        super.beforeUnSubmit(billContext);
    }

    /**
     * 获取 请购单 根据项目分组后求和的金额
     * @param billContext
     * @return
     * @throws Exception
     */
    private Map<String, BigDecimal> getProjectMoney(YpdBillContext billContext) throws Exception {
        String id = billContext.getBillDO().getPrimaryKey();
        Map<String, Object> applyOrder = MetaDaoHelper.findById(
                "zyhyspring2024.zyhyspring2024.dmm_apply_order",
                id
        );

        if (ObjectUtils.isEmpty(applyOrder)) {
            throw new BusinessException("请购单未找到");
        }

        List<Map<String, Object>> applyOrders = (List<Map<String, Object>>) applyOrder.get("dmm_apply_ordersList");
        if (ObjectUtils.isEmpty(applyOrders)) {
            throw new BusinessException("请购单表体未找到");
        }

        Map<String, BigDecimal> projectMoneyMap = applyOrders.stream().collect(Collectors.groupingBy(
                item -> Convert.toStr(item.get("project")),
                Collectors.mapping(
                        item -> Convert.toBigDecimal(item.get("money"), BigDecimal.ZERO),
                        Collectors.reducing(BigDecimal.ZERO, BigDecimal::add)
                )
        ));
        return projectMoneyMap;
    }


}
